import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, FormsModule],
  template: `
      <select [(ngModel)]="selectedVoice">
          <option value="">-选择一个声音-</option>
          <option *ngFor="let voice of voices" [ngValue]="voice">
              {{ voice.name }}
          </option>
      </select>
      <select [(ngModel)]="selectedRate">
          <option *ngFor="let rate of rates" [ngValue]="rate">
              {{ rate }}
              @if (rate === 1) {
                  (正常速度)
              }
          </option>
      </select>
      <br>
      <textarea [(ngModel)]="text" (keyup.enter)="start()"></textarea>
      <br>
      <button (click)="start()">朗读</button>
      <button (click)="stop()">停止</button>
      <button (click)="test()">test</button>
  `,
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  text = '';

  public sayCommand!: string;
  public rates!: number[];
  public selectedRate!: number;
  public selectedVoice!: SpeechSynthesisVoice | null;
  public voices!: SpeechSynthesisVoice[];

  constructor() {
    this.voices = [];
    this.rates = [.25, .5, .75, 1, 1.25, 1.5, 1.75, 2];
    this.selectedVoice = null;
    this.selectedRate = 1;
    // Dirty Dancing for the win!
    this.text = '你好呀嘿嘿嘿';
    this.sayCommand = '';
  }

  ngOnInit() {
    this.voices = speechSynthesis.getVoices();
    this.selectedVoice = this.voices[0] || null;
    if (!this.voices.length) {

      speechSynthesis.addEventListener(
          'voiceschanged',
          () => {
            this.voices = speechSynthesis.getVoices();
            console.log('voiceschanged', this.voices);

            this.selectedVoice = (this.voices[0] || null);
          },
      );

    }
  }

  start() {
    console.log(this.text);
    if (!this.selectedVoice || !this.text) return;
    this.stop();
    this.speak(this.selectedVoice, this.selectedRate, this.text);
  }

  speak(voice: SpeechSynthesisVoice,
        rate: number,
        text: string) {
    let utterance = new SpeechSynthesisUtterance(text);
    utterance.voice = voice;
    utterance.rate = rate;
    speechSynthesis.speak(utterance);
    utterance.onend = () => {
      console.log('读完了');
    };
  }

  stop() {
    if (speechSynthesis.speaking)
      speechSynthesis.cancel();
  }

  // cancel() {
  //   speechSynthesis.cancel();
  // }
  //
  // resume() {
  //   speechSynthesis.resume();
  // }

  test() {
    let voices = speechSynthesis.getVoices();
    console.log('voices', voices);
    console.log('speaking', speechSynthesis.speaking);
  }
}
